package com.example.myapplication4;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>{

    private List<bean> data;
    private Context context;
    //始终存在的并且创建之初就要有的通过构造方法传入
    public MyAdapter(Context context) {
        this.context = context;
    }
    //一开始可以没有，后续才会有的数据通过set方法传入
    public void setData(List<bean> data) {
        this.data = data;
    }

    //创建viewHodle对象，并且传入条目布局控件对象
    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull  ViewGroup parent, int viewType) {
        return new MyHolder(LayoutInflater.from(context).inflate(R.layout.list_item,null));
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyHolder holder, int position) {
        holder.contactName.setText(data.get(position).getName());
        holder.contactImg.setImageResource(data.get(position).getImg(R.mipmap.ic_launcher));

        //设置条目点击事件同ListView.setOnItemClickLister
        //对ViewHolder.itemView设置点击事件，与ListView.setOnItemClickLister效果相同
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context,"点击了："+data.get(position).getName(),Toast.LENGTH_SHORT).show();
            }
        });
        holder.contactImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context,"点击了："+data.get(position).getName()+"的头像",Toast.LENGTH_SHORT).show();
            }

        });
    }

    @Override
    public int getItemCount() {
        return null!=data?data.size():0;
    }

    class  MyHolder extends RecyclerView.ViewHolder{

        TextView contactName;
        ImageView contactImg;

        public MyHolder(@NonNull  View itemView) {
            super(itemView);
            //获取条目布局子控件
            contactName = itemView.findViewById(R.id.list_item_name);
            contactImg = itemView.findViewById(R.id.list_item_img);
        }
    }
}
